package com.dhcc.bpm.modules.content.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.constant.FilePathConstant;
import com.dhcc.bpm.common.docNode.ForestDocNodeMerge;
import com.dhcc.bpm.modules.common.entity.Upload;
import com.dhcc.bpm.modules.content.entity.DocDirectory;
import com.dhcc.bpm.modules.content.entity.DocManagement;
import com.dhcc.bpm.modules.content.mapper.DocDirectoryMapper;
import com.dhcc.bpm.modules.content.service.IDocDirectoryService;
import com.dhcc.bpm.modules.content.vo.DocDirectoryVO;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;

/**
 * @ClassName DocDirectoryServiceImpl
 * @Description  文档目录 服务实现类
 * @Author lijiacheng
 * @Date 2020/2/21 14:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */

@Service
public class DocDirectoryServiceImpl extends BaseServiceImpl<DocDirectoryMapper, DocDirectory> implements IDocDirectoryService {

	private String decompressUrl;
	private String docPath;
	@Value("${bpm.file-public-path}")
	public void setFileUploadPath(String publicPath) {
		decompressUrl = publicPath + FilePathConstant.ZIPPATH;
		docPath = publicPath + FilePathConstant.DOCPATH;
	}

	private int count;

	@Override
	public IPage<DocDirectoryVO> selectDocDirectoryPage(IPage<DocDirectoryVO> page, DocDirectoryVO docDirectory) {
		return page.setRecords(baseMapper.selectDocDirectoryPage(page, docDirectory));
	}

	@Override
	public List<DocDirectoryVO> tree() {
		return ForestDocNodeMerge.merge(baseMapper.tree());
	}

	@Override
	public int synInsertDirectory(String path, String opcDirectoryCode) {
		count = 0;
		DocDirectory docDirectory = baseMapper.selectMenuBycode(opcDirectoryCode);
		int orderNum = 0;
		if(docDirectory!=null) {
			orderNum = docDirectory.getOrderNum();
		}
		deleteDirectoryTree(opcDirectoryCode);
		synFile(path,orderNum,opcDirectoryCode);
		return count;
	}

	private void deleteDirectoryTree(String opcDirectoryCode) {
		DocDirectory docDirectory = new DocDirectory();
		docDirectory.setParentId(opcDirectoryCode);
		//检索docCode下所有的子节点，拿到所有子节点的主键
		//拿到二级目录
		List<DocDirectory> list = baseMapper.selectList(Condition.getQueryWrapper(docDirectory));
		if(list!=null &&list.size()!=0) {
			for (DocDirectory doc : list) {
				docDirectory.setParentId(doc.getDocCode());
				//拿到三级目录
				List<DocDirectory> list2 = baseMapper.selectList(Condition.getQueryWrapper(docDirectory));
				if(list2!=null &&list2.size()!=0) {
					for (DocDirectory doc2 : list2) {
						//根据三级子节点的主键删除所有的四级子节点
						baseMapper.deleteDocDirectoryChildByCode(doc2.getDocCode());
					}
				}
				//根据二级子节点的主键删除所有的三级子节点
				baseMapper.deleteDocDirectoryChildByCode(doc.getDocCode());
			}
		}
		//根据根节点的主键删除所有的二级子节点
		baseMapper.deleteDocDirectoryChildByCode(opcDirectoryCode);
	}

	public void synFile(String path,int orderNumRoot,String doc) {
		File file = new File(path);
		File[] files = file.listFiles();
		int orderNum = 0;
		if(files!=null) {
			for (File tempFile : files) {
				String fileName = tempFile.getName();
				String[] arry = fileName.split("_");
				if (tempFile.isDirectory() && arry.length == 5) {

					String url = tempFile.getAbsolutePath();
					String realUrl="";
					String type = arry[0].toLowerCase();
					String docType = selectDocType(type);
					String docCode = arry[1];
					String parentId = arry[2];
					String docName = arry[3];
					String perms = arry[4];
					DocDirectory docDirectory = new DocDirectory();
					docDirectory.setDocType(docType);
					docDirectory.setDocCode(docCode);
					docDirectory.setParentId(parentId);
					docDirectory.setDocName(docName);
					docDirectory.setPerms(perms);
					int p = url.replace("\\", "/").indexOf(decompressUrl.replace("\\", "/"));
					String rurl = url.substring(p+decompressUrl.length()-1);
					if("3".equals(docType))
					{
						docDirectory.setOrderNum(++orderNum);
						realUrl= rurl+"/index.html";
					}else if("1".equals(docType)){
						realUrl="#";
						if(docDirectory.getParentId()==null || "".equals(docDirectory.getParentId())) {
							docDirectory.setParentId("0");
						}
						docDirectory.setOrderNum(orderNumRoot);
					}else
					{
						docDirectory.setOrderNum(++orderNum);
						realUrl=rurl;
					}

					docDirectory.setUrl(realUrl.replace("\\", "/"));
					System.out.println(docDirectory.toString());
					if(!doc.equals(docCode)) {
						save(docDirectory);
						count++;
					}
					synFile(url,orderNumRoot,doc);
				}
			}
		}
	}

	//查询文档类型
	private String selectDocType(String type) {
		String  docType = "";
		if ("f".equals(type)) {
			docType =  "1";
		} else if ("m".equals(type)) {
			docType =  "2";
		} else if ("c".equals(type)) {
			docType =  "3";
		} else if ("w".equals(type)) {
			docType =  "4";
		}
		return docType;
	}

	@Override
	public String saveDocFile(DocManagement docManagement, Upload upload) {
		//根据文档编号查询文档一级目录
		String docCode = docManagement.getOpcDirectoryCode();
		DocDirectory doc = baseMapper.selectParentByChildcode(docCode);
		String parentId = doc.getParentId();
		DocDirectory docDirectory = baseMapper.selectMenuBycode(parentId);
		//转义文档类型
		String type = selectType(docDirectory.getDocType());
		String fileName = type + "_" + docDirectory.getDocCode()+"_" + docDirectory.getDocName();
		File docFile=new File(docPath + fileName);
		//文件夹不存在创建
		if(!docFile.exists()){
			docFile.mkdirs();
		}
		return fileName;
	}
	private String selectType(String docType) {
		String type = "";
		if ("1".equals(docType)){
			type = "f";
		}else if ("2".equals(docType)){
			type = "p";
		}else if ("3".equals(docType)){
			type = "c";
		}else if ("4".equals(docType)){
			type = "w";
		}
		return type;
	}

	private void saveFile(InputStream inputStream, String originalFilename) {
		try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(originalFilename))){
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = (inputStream.read(bytes))) > 0) {
				outputStream.write(bytes, 0, len);
			}
		} catch (FileNotFoundException e) {
			log.error("异常信息：{}", e);
		} catch (IOException e) {
			log.error("异常信息：{}", e);
		}finally {
			try {
				if(inputStream != null){
					inputStream.close();
				}
			} catch (IOException e) {
				log.error("异常信息：{}", e);
			}
		}
	}

	@Override
	public int removeDocByProductCode(String productCode) {
		return baseMapper.removeDocByProductCode(productCode);
	}

	@Override
	public int updateDocByProductCode(String productCode) {
		return baseMapper.updateDocByProductCode(productCode);
	}

	@Override
	public DocDirectoryVO findByDocCode(String docCode,  String productCode, String apiId) {
		return baseMapper.findByDocCode(docCode, productCode, apiId);
	}

	@Override
	public List<DocDirectoryVO> findByApiCode(String docCode) {
		return baseMapper.findByApiCode(docCode);
	}

	@Override
	public DocDirectoryVO findByDocCode(DocDirectory docDirectory) {
		return baseMapper.findByDoc(docDirectory);
	}

}
